package com.xiongjie.eb;

import com.xiongjie.util.CosUtil;
import com.xiongjie.util.PdfUtil;
import com.xiongjie.util.PebbleUtil;
import io.vertx.core.AsyncResult;
import io.vertx.core.Future;
import io.vertx.core.Handler;
import io.vertx.core.Vertx;
import io.vertx.core.json.JsonObject;
import io.vertx.serviceproxy.ServiceException;

import java.io.File;

public class IVppcProxyImpl implements IVppcProxy{

    private static String BASEPATH="src/main/resources/";
    private static String PDFPATH=BASEPATH+"pdf/";

    @Override
    public void renderUpload(String templateName, JsonObject json, Handler<AsyncResult<String>> resultHandler) {
        try {
            Vertx vertx= Vertx.vertx();
            PebbleUtil.render(vertx,templateName,json,ar -> {
                String html=ar.result();

                String fileName=json.getString("fileName");
                String pdfPath=PDFPATH+fileName;
                PdfUtil.covert(html,pdfPath);

                CosUtil.upload(vertx,pdfPath,res ->{
                    String cosPdfPath=res.result();

                    //删除本地生成的pdf文件
                    File file=new File(pdfPath);
                    file.delete();

                    resultHandler.handle(Future.succeededFuture(cosPdfPath));
                    vertx.close();
                });
            });
        }catch (Exception e){
            resultHandler.handle(ServiceException.fail(500,e.getMessage(),new JsonObject()));
        }
    }
}
